package xchange;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * Router listener class which runs in the same thread as the program so that
 * the program waits till the block file has been downloaded.
 * 
 * @author gijzerman
 * 
 */
public class RouterListener {

	private BufferedReader in = null;
	private FileInfoParser fp = null;

	/**
	 * Default constructor
	 * 
	 * @param in
	 *            - Socket connection with router
	 * @param fp
	 *            - Parser for the .!info files
	 */
	public RouterListener(BufferedReader in, FileInfoParser fp) {
		this.in = in;
		this.fp = fp;
	}

	/**
	 * Listen for input from the router
	 */
	public void listen() {

		String input = "";
		try {
			while ((input = in.readLine()) != null) {
				System.out.println("INPUT: " + input);
				parseCommand(input);

				if (input.equalsIgnoreCase("EOC")) {
					// When router sends End-of-command command stop listening
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Parse the input from the router
	 * 
	 * @param input
	 *            input from router
	 */
	private void parseCommand(String input) {
		if (input.startsWith("INFO-FILE")) {
			// create rt .!info files
			fp.createRTInfoFile(input);
		} else if (input.startsWith("BLOCK")) {
			// merge router files with local files
			MergeFiles mf = new MergeFiles();
			mf.mergeFile(input);
		}
	}

}
